package com.bc.web.controller.org;



import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.jxls.common.Context;

import com.bc.common.CommonEnum.NotifyStatus;
import com.bc.common.CommonEnum.OrderStatus;
import com.bc.web.config.SystemConfig;
import com.bc.web.config.SystemEnum.FilePath;
import com.bc.web.model.Dictionary;
import com.bc.web.model.OrgUser;
import com.bc.web.model.TradeOrder;
import com.fs.common.extend.FSController;
import com.fs.common.extend.FSSearchCondition;
import com.fs.common.util.FSExcel;
import com.fs.common.util.FSHttp;
import com.fs.common.util.FSLog;
import com.fs.common.util.FSThreadPoolExecutor;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Page;

public class TradeOrderController extends FSController {

	public void search() {
		OrgUser orgUser = (OrgUser) getSession().getAttribute("orgUser");
		FSSearchCondition sc = super.getSearchCondition();
		List<Dictionary> payTypeList = Dictionary.dao.selectPayType();
		Page<TradeOrder> pageResult = TradeOrder.dao.searchForOrg(sc, orgUser.getOrgCode());
		for (TradeOrder to : pageResult.getList()) {
			for (Dictionary payType : payTypeList) {
				if (to.getPayType().equals(payType.getCode())) {
					to.put("payTypeName", payType.getName());
					break;
				}
			}
		}
		setAttr("sumMoney", TradeOrder.dao.searchSumMoney(sc));
		setAttr("payTypeList", payTypeList);
		setAttr("orgCode",orgUser.getOrgCode());
		setPageResultToRequest("items", pageResult);
		render("order/orderList.html");
	}
	
	private static final String REPORT_PATH = PathKit.getWebRootPath()+File.separator +"payimg"+File.separator; //SystemEnum.FilePath.ReportTmp.getValue();
	@SuppressWarnings("unused")
	public void downloadzip() {
		OrgUser orgUser = (OrgUser) getSession().getAttribute("orgUser");
		File file = new File(REPORT_PATH + orgUser.getOrgCode() + ".zip");
		if(file == null) {
			renderFail("没有满足条件的数据:"+ REPORT_PATH + orgUser.getOrgCode() + ".zip");
		}else {
			renderFile(file);
		}
	}
	
	public void report() throws Exception {
		OrgUser orgUser = (OrgUser) getSession().getAttribute("orgUser");
		List<Dictionary> payTypeList = Dictionary.dao.selectPayType();
		Map<String,String> payTypeMap = new HashMap<>();
		for (Dictionary payType : payTypeList) {
			payTypeMap.put(payType.getCode(), payType.getName());
		}
		Map<String,String> orderStatus = new HashMap<>();
		for(OrderStatus os : OrderStatus.values()) {
			orderStatus.put(os.getValue(), os.getName());
		}
		
		FSSearchCondition sc = super.getSearchCondition();
		List<TradeOrder> items = TradeOrder.dao.searchReportForOrg(sc, orgUser.getOrgCode());
		for (TradeOrder item : items) {
			item.setPayType(payTypeMap.get(item.getPayType()));
			if(item.getNotifyStatus().equals(NotifyStatus.Wait.getValue())) {
				item.setNotifyStatus("未推");
			} else if (item.getNotifyStatus().equals(NotifyStatus.Success.getValue())) {
				item.setNotifyStatus("成功");
			} else {
				item.setNotifyStatus("失败");
			}
			item.setOrderStatus(orderStatus.get(item.getOrderStatus()));
			
		}
		String fileName = "交易明细报表";
		Context context = new Context();
		context.putVar("list", items);
		
		String templatePath = FilePath.ReportTemplate.getValue() + "trade_details.xlsx";
		String targetPath = FilePath.ReportTmp.getValue() + fileName + ".xlsx";
		LinkedHashMap<String, Context> sheetNameAndData = new LinkedHashMap<>();
		sheetNameAndData.put("交易明细", context);
		String[] templateSheetName = { "sheet1" };
		FSExcel.exportLargeData(templatePath, targetPath, sheetNameAndData, templateSheetName);
		File file = new File(targetPath);
		renderFile(file);
	}

	public void view() {
		TradeOrder tradeOrder = TradeOrder.dao.findById(getPara("id"));
		// 支付类别
		Dictionary dictionary = Dictionary.dao.selectByKey(tradeOrder.getPayType());
		tradeOrder.put("payTypeName", dictionary.getName());
		if(tradeOrder.getTotalFee() == null) {
			tradeOrder.put("totalFee", tradeOrder.getAmount());
		}
		setAttr("order", tradeOrder);
		
		List<TradeOrder> ogoRefOrderList = TradeOrder.dao.find(
				"select * from trade_order where originalOrderNo=? AND payType=? AND orderStatus is not NULL", tradeOrder.getOrderNo(),
				"wxgjpay_refund");
		if (ogoRefOrderList == null || ogoRefOrderList.isEmpty()) {
			setAttr("isRef", 0);
		} else {
			{
				setAttr("isRef", ogoRefOrderList.size());
				setAttr("ReforderList", ogoRefOrderList);
			}
		}
		
		render("order/orderView.html");
	}

	/**
	 * 推送
	 */
	public void push(){
		String[] ids = getParaValues("ids");
		FSThreadPoolExecutor.execute(new Runnable() {
			@Override
			public void run() {
				for (String id : ids) {
					try {
						String result = FSHttp.postString(SystemConfig.config.get("trade_system_url") + "/notify/adminPush", id);
						FSLog.web.info("商户补发通知结果 <-" + result);
					} catch (Exception e) {
						FSLog.web.error("商户补发通知异常",e);
					}
				}
			}
		});
		renderSuccess("补发通知成功",false);
	}
	
}
